import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
// import store from '@/store';
// import router from '@/router';
import router from '/@/router/index'
import { ElMessageBox, ElMessage } from 'element-plus';
import { loadEnv } from "@build/index";
import { getToken } from '/@/utils/auth'
// const service = axios.create({
// 	baseURL: process.env.NODE_ENV === 'development' ? devUrl : requestUrl,
// 	timeout: 5000
// })
const { VITE_PROXY_DOMAIN, VITE_PROXY_DOMAIN_REAL } = loadEnv();
// console.log(VITE_PROXY_DOMAIN_REAL, VITE_PROXY_DOMAIN)
const service = axios.create({
	baseURL:
		process.env.NODE_ENV === "production"
			? VITE_PROXY_DOMAIN_REAL
			: VITE_PROXY_DOMAIN,
	timeout: 5000 // 请求超时时间
})



service.interceptors.request.use(
	// 发送请求之前拦截
	(config: AxiosRequestConfig) => {
		if (getToken()) {
			config.headers['authorization'] = JSON.parse(getToken()).accessToken
		}
		return config;
	},
	(error: AxiosError) => {
		return Promise.reject(error);
	}
)








service.interceptors.response.use(
	(response: AxiosResponse) => {
		// 返回code值为200请求成功
		if (response.status === 200 || response.status === 201) {
			return Promise.resolve(response.data);
		} else {
			ElMessage.error(response.data.message);
			return Promise.reject(response.data);
		}
	},
	(error: AxiosError) => {
		// 回话过期
		if ((error.response as any).status == 403) {
			ElMessage.error('会话已过期')
			router.replace("/login");
		} else {
			// 其他错误
			ElMessage.error((error.response as any).data.message);
		}
		return Promise.reject(error);
	}
)



// const axios = function ({ path, method = "GET", data = {} }: any = {}) {
// 	return new Promise((resolve, reject) => {
// 		let datas: object = { params: { ...data } }
// 		if (method === "POST") datas = { ...{ data } };
// 		axios({
// 			url: `${config.host}${path}`,
// 			method,
// 			...datas
// 		}).then(res => {
// 			resolve(res.data)
// 		}).catch(err => { resolve(-1) })
// 	})
// };




export default service;
